package com.atguigu.gmall.product.service.impl;

import com.atguigu.gmall.product.mapper.BaseAttrInfoMapper;
import com.atguigu.gmall.product.model.BaseAttrInfo;
import com.atguigu.gmall.product.model.BaseAttrValue;
import com.atguigu.gmall.product.service.BaseAttrInfoService;
import com.atguigu.gmall.product.service.BaseAttrValueService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author terminal
 * @since 2023-06-05 22:43
 */
@Service
public class BaseAttrInfoServiceImpl extends ServiceImpl<BaseAttrInfoMapper,
        BaseAttrInfo> implements BaseAttrInfoService {

    @Resource
    private BaseAttrValueService baseAttrValueService;

    /**
     * 根据1,2,3级分类ID查询分类下关联平台属性列表(包含平台属性值)
     *
     * @param category1Id 一级分类ID
     * @param category2Id 二级分类ID
     * @param category3Id 三级分类ID
     * @return
     */
    @Override
    public List<BaseAttrInfo> getAttrInfoList(Long category1Id, Long category2Id, Long category3Id) {
        return this.baseMapper.getAttrInfoList(category1Id, category2Id, category3Id);
    }

    /**
     * 保存/修改平台属性以及平台属性值列表
     *
     * @param baseAttrInfo
     * @return
     */
    @Override
    public void saveAttrInfo(BaseAttrInfo baseAttrInfo) {
        if (baseAttrInfo.getId() != null) {
            //修改 先删除 再添加
            this.updateById(baseAttrInfo);
            LambdaQueryWrapper<BaseAttrValue> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(BaseAttrValue::getAttrId,baseAttrInfo.getId());
            baseAttrValueService.remove(queryWrapper);
            saveBaseAttrInfo(baseAttrInfo);
        } else {
            // 添加
            this.save(baseAttrInfo);
            this.saveBaseAttrInfo(baseAttrInfo);
        }
    }

    /**
     * 辅助上面两个方法的
     * @param baseAttrInfo
     */
    private void saveBaseAttrInfo(BaseAttrInfo baseAttrInfo) {
        List<BaseAttrValue> attrValueList = baseAttrInfo.getAttrValueList();
        attrValueList.stream().forEach(baseAttrValue -> {
            baseAttrValue.setAttrId(baseAttrInfo.getId());
        });
        baseAttrValueService.saveBatch(attrValueList);
    }

    /**
     * 根据平台属性ID 查询平台属性值列表
     *
     * @param attrId
     * @return
     */
    @Override
    public List<BaseAttrValue> getAttrValueList(Long attrId) {
        LambdaQueryWrapper<BaseAttrValue> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BaseAttrValue::getAttrId,attrId);
        return baseAttrValueService.list(queryWrapper);
    }
}
